package com.netty.service;

import com.alibaba.fastjson.JSON;
import com.netty.constant.BaseConstant;
import com.netty.domain.IMessage;
import com.netty.handler.WebSocketNettyHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;

/**
 * @author sixiaojie
 * @date 2020-03-30-20:10
 */
@Service
public class PushServiceImpl implements PushService {

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public void pushMsgToOne(IMessage message) {
        Map<String, ChannelHandlerContext> contextMap = WebSocketNettyHandler.getMAP();
        ChannelHandlerContext handlerContext = contextMap.get(message.getReceive());
        Channel channel = handlerContext.channel();
        if (!Objects.isNull(channel)) {
            // 如果该用户的客户端是与本服务器建立的channel,直接推送消息
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(message)));
        } else {
            redisTemplate.convertAndSend(BaseConstant.PUSH_MESSAGE_TO_ONE, JSON.toJSONString(message));
        }

    }

    @Override
    public void pushMsgToAll(IMessage message) {
        // 发布，给其他服务器消费
        redisTemplate.convertAndSend(BaseConstant.PUSH_MESSAGE_TO_ALL, JSON.toJSONString(message));
    }

}
